package com.study.SpringBootLesson4.springboot.filter;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 赵超
 * @Description springbootAPI注册filter学习
 * @create 2017-11-29 10:59
 **/
public class MyFilter2 extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse, FilterChain filterChain)
            throws ServletException, IOException {

//        ServletContext servletContext = httpServletRequest.getServletContext();
//        servletContext.log("myFilter2 " + httpServletRequest.getRequestURI() + " | " + httpServletRequest.getRequestURL());

        doSomeThing();
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    public void doSomeThing() {
        //另外，可以通过RequestContextHolder获取request
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        ServletContext servletContext = request.getServletContext();
        servletContext.log("myFilter2 " + request.getRequestURI() + " | " + request.getRequestURL());
    }
}
